//
//  InfoList.m
//  Trading365
//
//  Created by yifei tong on 12-1-10.
//  Copyright (c) 2012年 dhc. All rights reserved.
//

#import "QuotationList.h"
#import "TaskManager.h"
#import "XmlRpc.h"
#import "InfoType.h"
#import "QuotationListCell.h"
#import "QuotationInfo.h"
#import "QuotationAdd.h"
//#import "QuotPopupPanelView.h"
#import "QuotSelectList.h"
#import "AppDelegate.h"


@implementation QuotationList
@synthesize table;
@synthesize emploeeId,emploeePosiId,selectDays;


- (void)dealloc
{
    [toolDrawerView release];
    [table release]; 
    [emploeeId release];
    [emploeePosiId release];
    [selectDays release];
    [super dealloc];
}

- (id)init
{
	self = [super init];
	if(self)
	{
	}
	
	return self;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [self init];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    getflag = YES;
    _isSearching = NO;
    p_search=[NSString stringWithFormat:@""];
    self.search.showsCancelButton=NO;
    search_type=1;
    
    selectDays=@"1";

    self.title = @"最近一天报价";//+ INFO_STRING_QUOTATION;
    //self.navigationController.navigationBar.topItem.title = @"sfsfsafd";
    
//    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidenMenu)];
//    [self.navigationController.navigationBar addGestureRecognizer:singleTap];
    
    //search,new
    
    //设置导航栏背景颜色
    UIImage* imageBar = [UIImage imageNamed:PIC_MAIL_TOP_BAR];    
    UIToolbar* tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 110, 45)]; 

    NSString* devVersion = [[UIDevice currentDevice] systemVersion];
    if ([devVersion compare:@"4.3.3"] == 0)
    {
        [tools respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)];
        [tools setTintColor:NAVIGATION_BAR_COLOR];
    }else
    {
        [tools setBackgroundImage:imageBar forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    }
    NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:2];

    
    UIBarButtonItem *changeButton = [[UIBarButtonItem alloc] 
                                      initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize 
                                      target:self 
                                     action:@selector(changeDay)];
    
    UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] 
                                      initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
                                      target:self 
                                      action:@selector(find)];
    
    UIBarButtonItem *anotherButton1 = [[UIBarButtonItem alloc] 
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                       target:self 
                                       action:@selector(add)]; 
    
    [buttons addObject:changeButton]; 
    [changeButton release]; 
    [buttons addObject:anotherButton]; 
    [anotherButton release]; 
    [buttons addObject:anotherButton1]; 
    [anotherButton1 release]; 
    [tools setItems:buttons animated:NO]; 
    [buttons release]; 
    UIBarButtonItem *myBtn = [[UIBarButtonItem alloc] initWithCustomView:tools]; 
    self.navigationItem.rightBarButtonItem = myBtn;
    [myBtn release]; 
    [tools release];
    
    currentSelectMenuIndex = 0;
    oldSelectMenuIndex = 0;
    
    //弹出bar
	UIButton *button;
    toolDrawerView = [[ToolDrawerView alloc]initInVerticalCorner:kTopCorner andHorizontalCorner:kLeftCorner moving:kVertically];
    [toolDrawerView SetSize:45 height:40]; 
    //[toolDrawerView SetCtlPos:CGPointMake(210, 183)];
    [toolDrawerView SetCtlPos:CGPointMake(210, 201)];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.viewController.view addSubview:toolDrawerView];
    
    UIImage* imageView = [UIImage imageNamed:PIC_INFO_DRAG_MENU];
    UIImageView* personImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, -16, 136.5, 72)];
    [personImage setImage:imageView];
    
    [toolDrawerView addSubview:personImage];
    
    [personImage release];
    
    //一天
	button = [UIButton buttonWithType:UIButtonTypeCustom];
    //[button setBackgroundImage:dragMenuImg forState:UIControlStateNormal];
	[button setTitle:@"一天" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.tag=1;
    [button addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];  //设置按钮点击事件   
	[toolDrawerView appendButton:button];
    
    //一周
	button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setTitle:@"一周" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //[button setBackgroundImage:dragMenuImg forState:UIControlStateNormal];

    button.tag=2;
    [button addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];  //设置按钮点击事件   
	[toolDrawerView appendButton:button];
    
    //一月
	button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setTitle:@"一月" forState:UIControlStateNormal];
     //[button setBackgroundImage:dragMenuImg forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.tag=3;
    [button addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];  //设置按钮点击事件   
	[toolDrawerView appendButton:button];
    //隐藏弹出菜单
    toolDrawerView.hidden = YES;
    
    //search bar
    search = [[UISearchBar alloc] init];
	[search setScopeButtonTitles:[NSArray arrayWithObjects:@"报价单号",@"客户名称",nil]];//报价单号 01 客户中文名称 02
	search.delegate = (id)self;
	[search setAutocapitalizationType:UITextAutocapitalizationTypeNone];
	[search sizeToFit];
    
    //如何修改UISearchBar的scopeBar的背景颜色
    search.tintColor = NAVIGATION_BAR_COLOR;  
    search.backgroundColor=[UIColor clearColor];  

    [self changePlaceholder];
    self.search.showsCancelButton=NO;
    
	self.tableView.tableHeaderView = search;
	/*
	 fix the search bar width problem in landscape screen
	 */
	if (UIInterfaceOrientationLandscapeRight == [[UIDevice currentDevice] orientation] ||
		UIInterfaceOrientationLandscapeLeft == [[UIDevice currentDevice] orientation])
	{
		self.tableView.tableHeaderView.frame = CGRectMake(0.f, 0.f, 480.f, 44.f);
	}
	else
	{
		self.tableView.tableHeaderView.frame = CGRectMake(0.f, 0.f, 320.f, 44.f);
	}
	/*
	 set up the searchDisplayController programically
	 */
	searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:search contentsController:self];
	[self setSearchDisplayController:searchDisplayController];
	[searchDisplayController setDelegate:(id)self];
	[searchDisplayController setSearchResultsDataSource:self];
    
//	[mySearchBar release];
    self.tableView.scrollEnabled = YES;
    [self.tableView setContentOffset:CGPointMake(0, 44.f) animated:NO];
    
    [self refreshData];
    [self.table reloadData];
        
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    table=nil;
}

- (void)viewWillAppear:(BOOL)animated {
	/*
	 Hide the search bar
	 */
	[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:NO];
//	ppv = nil;
}

- (void)viewWillDisappear:(BOOL)animated{
    if (toolDrawerView.hidden == NO)
        toolDrawerView.hidden=YES;
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Table view data source
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [responseParams count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"QuotationListCell";
    
    QuotationListCell* cell = (QuotationListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil){
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"QuotationListCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    // Configure the cell...
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
   
    if (indexPath.row>[responseParams count]) {
        return cell;
    }

    if ([responseParams count] < 1)
        return cell;
    NSUInteger row = [indexPath row];
    
    NSMutableDictionary* dic = nil;
    if (indexPath.row < [responseParams count]) 
    {
        dic = [[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:row]] ;
    }else
    {
        dic = [[NSMutableDictionary alloc] initWithCapacity:0];
    }

    cell.quotPriceNo.text = [dic objectForKey:@"price_quote_no"];
    cell.quotCustName.text=[dic objectForKey:@"customer_short_name"];
    cell.quotStatus.text=@"";
    cell.quotOrgcnyAmout.text=[dic objectForKey:@"name"];;
    cell.quotEmployee.text=[dic objectForKey:@"quote_date"];
        
    [dic release];
    
    return cell;
    
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary* tmp_dictionary = nil;
    if (indexPath.row < [responseParams count]) 
    {
        tmp_dictionary = [[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:indexPath.row]];
    }else
    {
        tmp_dictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    }
    
    NSString *p_no=[NSString stringWithFormat:@"%@",[tmp_dictionary valueForKey:@"price_quote_no"]];
    NSString *p_id=[NSString stringWithFormat:@"%@",[tmp_dictionary valueForKey:@"price_quote_id"]];
    
    QuotationInfo *detail = [[QuotationInfo alloc] init];
    [detail setQuotationNO:p_no];
    [detail setQuotationID:p_id];
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    [tmp_dictionary release];

}


#pragma mark - UserTask

-(void) OnPreExcute
{
    [super OnPreExcute];
}

-(void) OnPostExcute
{    
    [super OnPostExcute];
}

-(void) DoInBackground
{
    if (getflag == NO && _isSearching == NO) {
        return;
    }
    startRow = [responseParams count];
    NSString *num = [NSString stringWithFormat:@"%i",startRow];
    NSString *rowsperpage = [NSString stringWithFormat:@"%i",PER_PAGE_ROWS];
    NSMutableArray *tmp=nil;
    XmlRpc *xml = [[XmlRpc alloc] init];

    if (_isSearching){
        tmp = [xml GetSearchQuotationList:p_search Type:[NSString stringWithFormat:@"0%d",search_type] startRows:num  rowsPerPage:rowsperpage];       
    }else{
        tmp = [xml GetQuotationList:[[Session share] getMemberID] period:selectDays positionID:[[Session share] getMemberPosiID] startRows:num rowsPerPage:rowsperpage];  
    }
    
    NSMutableArray *tmp_arry=[[NSMutableArray alloc] initWithArray:tmp]; 
    
    for (NSMutableDictionary* itq in tmp_arry) {
        [responseParams addObject:itq];
    }

    if ([tmp_arry count]<PER_PAGE_ROWS) {
        getflag = NO;
        _isSearching=NO;
    }
    
    [tmp_arry release];
    [xml release];

    [self.table reloadData];
}


#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{

    NSString *tmp=[[NSString alloc] initWithFormat:@"%@",searchString];
	p_search = tmp;    
    search_type=[self.searchDisplayController.searchBar selectedScopeButtonIndex]+1;
    
    // Return YES to cause the search result table view to be reloaded.
    return NO;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption{
    
    search_type=searchOption+1;

    // Return YES to cause the search result table view to be reloaded.
    return NO;
}

- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller{
	
	[self.searchDisplayController.searchResultsTableView setDelegate:self];
}


- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller{
    //Hide the search bar
	[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:YES];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self doSearch];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    if (self.search.showsCancelButton==NO)
        self.search.showsCancelButton=YES;
    
    [self hidenMenu];
    [self changePlaceholder];
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    self.search.showsCancelButton=NO;
    [self.search resignFirstResponder];
}

#pragma mark - my function

- (void)doSearch{
    [super doSearch];
        
    self.title = @"报价";
    oldSelectMenuIndex = 0;
    [self.table reloadData];
    
    [[[TaskManager Share] GetTaskByType:GetQuotationInfoList Delegate:self] Excute];
}


-(void)refreshData
{    
    [[[TaskManager Share] GetTaskByType:GetQuotationInfoList Delegate:self] Excute];
}

-(void) getMoreData
{
    [[[TaskManager Share] GetTaskByType:GetQuotationInfoList Delegate:self] Excute];
}

-(void)add
{
    QuotationAdd *add=[[QuotationAdd alloc] init];
    [self.navigationController pushViewController:add animated:YES];
    [add release];
    
}

-(void)find
{
    [self hidenMenu];
    
    [super find];

}

-(void)changeDay{
    if (toolDrawerView.hidden){
        toolDrawerView.hidden = NO;
    }
    else{
        toolDrawerView.hidden = YES; 
    }
}

-(void)change:(id)sender
{    
    ////////menu
    [self changeDay];
    
    UIButton *btn = (UIButton *)sender;
    
    currentSelectMenuIndex = btn.tag;
    
    if (oldSelectMenuIndex == currentSelectMenuIndex)
    {
        return;
    }
    
    oldSelectMenuIndex = currentSelectMenuIndex;
    selectDays = @"1";
    self.title = @"最近一天报价";
    
    if (currentSelectMenuIndex == 2){
        selectDays = @"2";
        self.title = @"最近一周报价";
    }
    if (currentSelectMenuIndex == 3){
        selectDays = @"3";
        self.title = @"最近一月报价";
    }
    
    getflag = YES;
    _isSearching = NO;
    self.navigationItem.leftBarButtonItem.enabled=NO;
    [responseParams removeAllObjects];
    
//    NSLog(@"Select:%d",currentSelectMenuIndex);
    [self refreshData];
    [self.table reloadData];
}

-(void)hidenMenu
{
    if (toolDrawerView.hidden == NO)
        toolDrawerView.hidden=YES;
}

@end
